package com.poetry.vup.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.poetry.vup.common.entity.user.VupUserDO;
import com.poetry.vup.common.result.page.BasePage;
import com.poetry.vup.common.result.page.PageParam;
import com.poetry.vup.common.util.JacksonUtil;
import com.poetry.vup.common.util.PageUtils;
import com.poetry.vup.user.domain.VupUserDTO;
import com.poetry.vup.user.domain.VupUserVO;
import com.poetry.vup.user.mapper.VupUserMapper;
import com.poetry.vup.user.service.VupUserAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
@Slf4j
public class VupUserAuthServiceImpl implements VupUserAuthService {

    @Autowired
    private VupUserMapper vupUserMapper;

    /**
     * 查找所有的用户
     * @return
     * @param pageSize
     * @param pageNum
     */
    @Override
    public BasePage<VupUserVO> findAllVupUser(int pageSize, int pageNum) {

        List<VupUserVO> list = new ArrayList<>();
        BasePage<VupUserVO> page = new BasePage<>();

        int offset = (pageNum-1) * pageSize;//计算偏移量
        if(offset < 0){
            offset = 1;
        }

        Long count = null;
        list = vupUserMapper.findAllVupUser(offset,pageSize);//所有用户列表
        count = vupUserMapper.getCount();

        if(list != null && list.size() != 0){
            return PageUtils.buildBasePage(list,new PageParam(pageNum,pageSize),count);
        }else {
            page.setList(list);
        }

        return page;
    }

    @Override
    public VupUserVO findById(Long id) {
        return JacksonUtil.objectToObject(vupUserMapper.selectById(id),VupUserVO.class);
    }

    /**
     * 登录
     * @param userName
     * @param passWord
     * @return
     */
    @Override
    public VupUserVO findUserNameAndPassWord(String userName, String passWord) {
        VupUserVO vupUserVO = vupUserMapper.findUserNameAndPassWord(userName,passWord);
        if(vupUserVO != null){
            return vupUserVO;
        }
        return null;
    }

    /**
     * 修改
     * @param vupUserDTO
     * @return
     */
    @Override
    public int update(VupUserDTO vupUserDTO) {
        int i = vupUserMapper.updateById(JacksonUtil.objectToObject(vupUserDTO, VupUserDO.class));
        return i;
    }

    @Override
    public VupUserDO findByUserName(String userName) {
        QueryWrapper<VupUserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userName);
        VupUserDO vupUserDO = vupUserMapper.selectOne(queryWrapper);
        return vupUserDO;
    }
}
